package com.nycreativity.elecreativity.controller


import com.nycreativity.elecreativity.aop.ValidateAspect
import com.nycreativity.elecreativity.entity.cons.CommonURLConstants
import com.nycreativity.elecreativity.entity.ResultData
import com.nycreativity.elecreativity.entity.param.activity.ActivityAddParam
import com.nycreativity.elecreativity.entity.param.activity.ActivityQueryParam
import com.nycreativity.elecreativity.entity.param.activity.ActivityUpdateParam
import com.nycreativity.elecreativity.entity.po.Activity
import com.nycreativity.elecreativity.entity.vo.PageDataVO
import com.nycreativity.elecreativity.entity.vo.activity.ActivityVO
import com.nycreativity.elecreativity.service.ActivityService
import com.nycreativity.elecreativity.util.MappingUtil
import io.swagger.annotations.Api
import io.swagger.annotations.ApiOperation
import org.springframework.transaction.annotation.Transactional
import org.springframework.validation.AbstractBindingResult
import org.springframework.validation.BindingResult
import org.springframework.web.bind.annotation.*

import javax.annotation.Resource
import javax.validation.Valid

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author sxt && ttxxi
 * @since 2021-03-10
 */
@RestController
@RequestMapping(CommonURLConstants.ACTIVITY_PREFIX)
@Api(tags = ["活动相关接口"])
class ActivityController {

    @Resource
    lateinit var activityService: ActivityService

    @PostMapping
    @ApiOperation("添加活动")
    fun addActivity(activity: ActivityAddParam): ResultData<Boolean> {
        val rs = activityService.addActivity(activity)
        return if (rs) ResultData.SUCCESS("活动添加成功") else ResultData.FAILED("活动添加失败")
    }

    @GetMapping
    @ApiOperation("查询活动")
    fun getActivity(activityQueryParam: ActivityQueryParam): ResultData<PageDataVO<ActivityVO>> {
        val activities = activityService.queryActivity(activityQueryParam)
        val results: ResultData<PageDataVO<ActivityVO>> = ResultData.SUCCESS()
        results.data = activities
        return results
    }

    @PutMapping("{id}")
    @ApiOperation("修改活动")
    @ValidateAspect.ParamValidate
    fun updateActivity(
        @PathVariable("id") id: Long,
        @Valid activityUpdateParam: ActivityUpdateParam,
        bindingResult: BindingResult
    ): ResultData<Boolean> {
        val activity = MappingUtil.getMappingObject(activityUpdateParam, Activity::class.java)
        activity?.id = id
        activity.modify()
        return if (activityService.updateById(activity)) ResultData.SUCCESS("活动修改成功") else ResultData.FAILED("活动修改失败")
    }

    @DeleteMapping("{id}")
    @ApiOperation("删除活动")
    @Transactional
    fun removeActivity(@PathVariable id: Long): ResultData<Boolean> {
        val activity = Activity(id)
        activity.modify()
        return if (activityService.updateById(activity) && activityService.removeById(id)) ResultData.SUCCESS("活动删除成功") else ResultData.FAILED("活动删除失败")

    }

}
